package translate;

import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

import config.CLResourceBundleManager;

import db.beans.M_WebsiteBean;
import db.beans.T_KeywordBean;
import db.tables.M_DictionaryTable;
import db.tables.T_DictionaryTable;
import db.tables.T_KeywordTable;

public class TranslateManager {
	private String[] dictionaryArray_ = null;
	private Connection conn_;
	private Map<String, String> mapKeyword_ = new HashMap<String, String>();;
	private M_WebsiteBean objTargetWebsite_;

	public TranslateManager(Connection conn, M_WebsiteBean objTargetWebsite)throws Exception{
		conn_ = conn;
		objTargetWebsite_ = objTargetWebsite;
		dictionaryArray_ = M_DictionaryTable.selectDictionaryTableNameByLanguageId(conn, objTargetWebsite.getLanguageId());
		initKeywordMap();
	}

	public String translate(String srcKeyword) throws Exception{
		String desWord = "";
		if (dictionaryArray_ != null && dictionaryArray_.length > 0){
			String[] arrDesWord = new String[dictionaryArray_.length];
			for (int i = 0; i < dictionaryArray_.length; i++){
				arrDesWord[i] = T_DictionaryTable.selectDesKeywordBySrcKeyword(conn_, dictionaryArray_[i], srcKeyword);
			}

			String firstKeyword = "";
			int count = 0;
			for (int i = 0; i < arrDesWord.length; i++){
				if (i == 0){
					if (arrDesWord[i] != null && !"".equals(arrDesWord[i])){
						firstKeyword = arrDesWord[i];
						count++;
					}

				} else {
					if (arrDesWord[i] != null && !"".equals(arrDesWord[i])){
						if ("".equals(firstKeyword)){
							firstKeyword = arrDesWord[i];
							count++;
						} else {
							if (firstKeyword.equals(arrDesWord[i])){
								count++;
							}
						}
					}
				}
			}

			if (count == 0){
				return desWord;
			}
		}

		return desWord;
	}

	public String getDesKeyword(String srcKeyword) throws Exception{
		String desKeyword = mapKeyword_.get(srcKeyword);
		if (desKeyword == null){
			T_KeywordTable.selectDesKeywordBySrcKeyword(conn_, objTargetWebsite_.getSearchKeywordTableName(), srcKeyword);
		}

		return desKeyword;
	}

	private void initKeywordMap() throws Exception{
		int cacheMaxSize = CLResourceBundleManager.getCacheMaxSize();
		T_KeywordBean[] objKeyword = T_KeywordTable.selectByTopCount(conn_, objTargetWebsite_.getSearchKeywordTableName(), cacheMaxSize);

		for (int i = 0; i < objKeyword.length; i++){
			mapKeyword_.put(objKeyword[i].getSrcKeyword(), objKeyword[i].getDesKeyword1());
		}
	}

}
